// lib/controllers/buy_record_controller.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:drift/drift.dart' as drift;

import '../../../core/network/stock_api_service.dart';
import '../../../data/models/buy_record_model.dart';

import '../../../data/models/sell_record_model.dart';
import '../../../data/datasource/local/database.dart';


class BuyRecordController extends GetxController {
  final AppDatabase _database = Get.find();
  final StockApiService _apiService = Get.find();

  var isLoading = false.obs;
  var buyRecords = <BuyRecordModel>[].obs;
  var sellRecords = <SellRecordModel>[].obs;
  var filteredRecords = <BuyRecordModel>[].obs;
  var errorMessage = ''.obs;
  var searchQuery = ''.obs;

  @override
  void onInit() {
    super.onInit();
    fetchBuyRecords();
  }

  // 获取所有买入记录
  Future<void> fetchBuyRecords() async {
    try {
      isLoading(true);
      errorMessage('');

      // 从数据库获取记录
      final records = await _database.allBuyRecords;

      // 转换为 BuyRecordModel
      final recordModels = records.map((record) => BuyRecordModel(
        id: record.id,
        symbol: record.symbol,
        name: record.name,
        buyPrice: record.buyPrice,
        quantity: record.quantity,
        remainingQuantity: record.remainingQuantity,
        buyDate: record.buyDate,
        createdAt: record.createdAt,
      )).toList();

      buyRecords.assignAll(recordModels);

      // 获取卖出记录
      await fetchSellRecords();

      _filterRecords();
    } catch (e) {
      errorMessage('获取买入记录失败: $e');
    } finally {
      isLoading(false);
    }
  }

  // 获取所有卖出记录
  Future<void> fetchSellRecords() async {
    try {
      final records = await _database.allSellRecords;

      // 转换为 SellRecordModel
      final recordModels = records.map((record) => SellRecordModel(
        id: record.id,
        buyRecordId: record.buyRecordId,
        sellPrice: record.sellPrice,
        sellQuantity: record.sellQuantity,
        sellDate: record.sellDate,
      )).toList();

      sellRecords.assignAll(recordModels);
    } catch (e) {
      errorMessage('获取卖出记录失败: $e');
    }
  }

  // 根据股票代码获取股票名称
  Future<String?> getStockName(String symbol) async {
    try {
      final data = await _apiService.fetchStockData(symbol);
      final parts = data.split(',');
      return parts[0].replaceAll('"', '');
    } catch (e) {
      errorMessage('获取股票信息失败: $e');
      return null;
    }
  }

  // 在 BuyRecordController 中修改 addBuyRecord 方法
  Future<bool> addBuyRecord({
    required String symbol,
    required String name,
    required double buyPrice,
    required int quantity,
    required DateTime buyDate,
  }) async {
    try {
      final companion = BuyRecordsCompanion(
        symbol: drift.Value(symbol),
        name: drift.Value(name),
        buyPrice: drift.Value(buyPrice),
        quantity: drift.Value(quantity),
        remainingQuantity: drift.Value(quantity), // 初始剩余数量等于买入数量
        buyDate: drift.Value(buyDate),
      );

      await _database.insertBuyRecord(companion);
      await fetchBuyRecords();

      // 移除这里的 Snackbar 显示，由视图层处理
      return true;
    } catch (e) {
      // 移除这里的 Snackbar 显示，由视图层处理
      return false;
    }
  }

  // 更新买入记录 - 移除成功提示
  Future<bool> updateBuyRecord({
    required int id,
    required String symbol,
    required String name,
    required double buyPrice,
    required int quantity,
    required DateTime buyDate,
  }) async {
    try {
      // 获取原始记录
      final originalRecord = await _database.getBuyRecordById(id);
      if (originalRecord == null) {
        throw Exception('记录不存在');
      }

      // 计算新的剩余数量（考虑已卖出部分）
      int newRemainingQuantity = quantity;
      if (quantity < originalRecord.quantity) {
        // 如果新数量小于原数量，需要调整剩余数量
        final soldQuantity = originalRecord.quantity - originalRecord.remainingQuantity;
        newRemainingQuantity = quantity - soldQuantity;
        if (newRemainingQuantity < 0) {
          throw Exception('新数量不能小于已卖出数量');
        }
      }

      // 更新记录
      final companion = BuyRecordsCompanion(
        id: drift.Value(id),
        symbol: drift.Value(symbol),
        name: drift.Value(name),
        buyPrice: drift.Value(buyPrice),
        quantity: drift.Value(quantity),
        remainingQuantity: drift.Value(newRemainingQuantity),
        buyDate: drift.Value(buyDate),
      );

      // 使用正确的更新方法
      await (_database.update(_database.buyRecords)..where((tbl) => tbl.id.equals(id))).write(companion);

      await fetchBuyRecords();

      // 移除了成功提示，只返回成功状态
      return true;
    } catch (e) {
      // 移除了错误提示，只返回失败状态
      return false;
    }
  }

  // 卖出股票
  Future<bool> sellStock({
    required int buyRecordId,
    required double sellPrice,
    required int sellQuantity,
    required DateTime sellDate,
  }) async {
    try {
      // 获取原始记录
      final originalRecord = await _database.getBuyRecordById(buyRecordId);
      if (originalRecord == null) {
        throw Exception('记录不存在');
      }

      // 检查卖出数量是否有效
      if (sellQuantity > originalRecord.remainingQuantity) {
        throw Exception('卖出数量不能超过剩余数量');
      }

      // 插入卖出记录
      final sellCompanion = SellRecordsCompanion(
        buyRecordId: drift.Value(buyRecordId),
        sellPrice: drift.Value(sellPrice),
        sellQuantity: drift.Value(sellQuantity),
        sellDate: drift.Value(sellDate),
      );

      await _database.insertSellRecord(sellCompanion);

      // 更新买入记录的剩余数量
      final newRemainingQuantity = originalRecord.remainingQuantity - sellQuantity;
      await _database.updateRemainingQuantity(buyRecordId, newRemainingQuantity);

      await fetchBuyRecords();

      Get.snackbar(
        '成功',
        '已记录卖出操作',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[900],
        duration: const Duration(seconds: 2),
      );

      return true;
    } catch (e) {
      Get.snackbar(
        '错误',
        '卖出操作失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
      return false;
    }
  }

  // 删除买入记录
  Future<void> deleteBuyRecord(int id) async {
    try {
      // 先删除相关的卖出记录
      final sellRecords = await _database.getSellRecordsByBuyId(id);
      for (final record in sellRecords) {
        await _database.deleteSellRecord(record.id);
      }

      // 删除买入记录
      await _database.deleteBuyRecord(id);
      await fetchBuyRecords();

      Get.snackbar(
        '成功',
        '已删除买入记录及相关卖出记录',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[900],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '删除买入记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
    }
  }

  // 删除卖出记录
  Future<void> deleteSellRecord(int id, int buyRecordId) async {
    try {
      // 获取卖出记录
      final sellRecords = await _database.getSellRecordsByBuyId(buyRecordId);
      final sellRecord = sellRecords.firstWhere((record) => record.id == id);

      // 获取买入记录
      final buyRecord = await _database.getBuyRecordById(buyRecordId);
      if (buyRecord == null) {
        throw Exception('买入记录不存在');
      }

      // 删除卖出记录
      await _database.deleteSellRecord(id);

      // 恢复买入记录的剩余数量
      final newRemainingQuantity = buyRecord.remainingQuantity + sellRecord.sellQuantity;
      await _database.updateRemainingQuantity(buyRecordId, newRemainingQuantity);

      await fetchBuyRecords();

      Get.snackbar(
        '成功',
        '已删除卖出记录',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[900],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '删除卖出记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
    }
  }

  // 根据ID获取买入记录
  Future<BuyRecordModel?> getBuyRecordById(int id) async {
    try {
      final record = await _database.getBuyRecordById(id);
      if (record == null) return null;

      return BuyRecordModel(
        id: record.id,
        symbol: record.symbol,
        name: record.name,
        buyPrice: record.buyPrice,
        quantity: record.quantity,
        remainingQuantity: record.remainingQuantity,
        buyDate: record.buyDate,
        createdAt: record.createdAt,
      );
    } catch (e) {
      errorMessage('获取买入记录失败: $e');
      return null;
    }
  }

  // 根据搜索查询过滤记录
  void setSearchQuery(String query) {
    searchQuery.value = query;
    _filterRecords();
  }

  // 过滤记录
  void _filterRecords() {
    if (searchQuery.isEmpty) {
      filteredRecords.assignAll(buyRecords);
    } else {
      final query = searchQuery.value.toLowerCase();
      filteredRecords.assignAll(buyRecords.where((record) {
        return record.symbol.toLowerCase().contains(query) ||
            record.name.toLowerCase().contains(query);
      }).toList());
    }
  }
}